package com.xixudi.htmlto;

import com.jfinal.kit.StrKit;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * @desc 执行命令的帮助类
 * @author YangZheng 328170112@qq.com
 * @date 2019-02-22 21:46
 */
public class CommandHelper {
    private ProcessBuilder pb;
    private String command;
    private String[] envp;
    private File dir;
    private String[] cmdarray;
    public CommandHelper(String command, String[] envp, String dirPath) {
        this.envp = envp;
        if(dirPath!=null) dir = new File(dirPath);
        if (command.length() == 0) throw new IllegalArgumentException("Empty command");
        this.command = command;
        StringTokenizer st = new StringTokenizer(command);
        cmdarray = new String[st.countTokens()];
        for (int i = 0; st.hasMoreTokens(); i++)
            cmdarray[i] = st.nextToken();
        getPb();
    }

    public CommandHelper(String[] cmdarray, String[] envp, String dirPath) {
        this.envp = envp;
        if(dirPath!=null) dir = new File(dirPath);
        this.cmdarray = cmdarray;
        this.command = StrKit.join(cmdarray);
        getPb();
    }
    public ProcessBuilder getPb(){
        if(pb == null) {
            pb = new ProcessBuilder(cmdarray);
            Map<String, String> env = pb.environment();
            if (envp != null) {
                for (String envstring : envp) {
                    if (envstring.indexOf((int) '\u0000') != -1) envstring = envstring.replaceFirst("\u0000.*", "");
                    int eqlsign = envstring.indexOf('=', 1);
                    if (eqlsign != -1) env.put(envstring.substring(0, eqlsign), envstring.substring(eqlsign + 1));
                }
            }
            pb.redirectErrorStream(true);//重定向错误流到输入流,一起打印,防止缓存满
            pb.directory(dir);
        }
        return pb;
    }
    public void run() {
        System.out.println("command:"+command+"dir:"+dir);
        BufferedReader reader = null;
        try {
            Process p = getPb().start();
            reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String s = null;
            int a = 0;
            while ((s = reader.readLine()) != null) {
                if(a > 0) {
                    while (a-->0) System.out.print("\b");
                } else if(a!=0 && !"".equals(s)){
                    System.out.println();
                }
                if(!"".equals(s)) {
                    if(s.matches("[^\\n]*\\[[=*>\\s]+\\][^\\n]*")) {
                        a = s.length();
                    }
                    System.out.print(s);
                    if(a==0) a=-1;
                }
            }
            p.waitFor();
            System.out.println();
            System.out.println("execute end");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void run(String command,String[] envp, String dir) {
        new CommandHelper(command, envp, dir).run();
    }
}
